package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.api.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.NewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @Description TODO
 * @Author bo.li
 * @Date 2023/3/20 15:19
 * @Version 1.0
 */
@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {


    public final static int TASK_TYPE  = 200;
    public final static int TASK_PRIORITY  = 1;

    @Autowired
    private IScheduleClient scheduleClient;
    @Autowired
    private NewsAutoScanService newsAutoScanService;
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    public void addTask(WmNews wmNews) {
        Task task = new Task();
        task.setTaskType(TASK_TYPE);
        task.setPriority(TASK_PRIORITY);
        task.setExecuteTime(wmNews.getPublishTime().getTime());
        WmNews newParam = new WmNews();
        newParam.setId(wmNews.getId());
        task.setParameters(ProtostuffUtil.serialize(newParam));
        ResponseResult result = scheduleClient.addTask(task);
        log.info("添加任务返回参数：{}", JSON.toJSONString(result));
    }


    @Scheduled(cron = "* * */5 * * ?")
    public void pollTask(){
        log.info("开始执行拉取任务");
        ResponseResult result = scheduleClient.poll(TASK_TYPE, TASK_PRIORITY);
        log.info("拉取任务结果：{}",JSON.toJSONString(result));
        if(result.getCode() != AppHttpCodeEnum.SUCCESS.getCode() || result.getData() == null){
            return;
        }
        String taskJson = JSON.toJSONString(result.getData());
        Task task = JSON.parseObject(taskJson, Task.class);

        //注意：这里的wmNews只有id，没有其他，需要重新查询
        WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
        WmNews wmNewsAllInfo = wmNewsMapper.selectById(wmNews.getId());
        newsAutoScanService.newsScan(wmNewsAllInfo);
    }
}